package com.gulimall.product.app;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gulimall.common.core.domain.Result;
import com.gulimall.common.valid.AddGroup;
import com.gulimall.common.valid.UpdateGroup;
import com.gulimall.product.domain.entity.Category;
import com.gulimall.product.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 商品三级分类 前端控制器
 * </p>
 *
 * @author 坤哥
 * @since 2025-08-25
 */
@Slf4j
@RestController
@RequestMapping("/product/category")
public class CategoryController {
    @Resource
    private ICategoryService categoryService;

    /**
     * 查询所有分类及子分类
     */
    @GetMapping("/getProductCategory")
    public Result<List<Category>> getProductCategory(){
        log.info("查询所有分类及子分类:");
        List<Category> categories =  categoryService.getProductCategory();
        return Result.ok(categories);
    }

    /**
     * 批量或单个删除商品
     */
    @DeleteMapping("/deleteProduct")
    public Result deleteProduct(@RequestBody List<Long> catIds){
        log.info("要删除的商品id为：{}",catIds);
        return categoryService.deleteProduct(catIds);
    }

    /**
     * 保存商品
     * 参数校验时只有指定group的字段才能进行校验
     * 如果不加@Validated，那么只有不加group的字段才能校验
     */
    @PostMapping("/saveProduct")
    public Result saveProduct(@Validated(AddGroup.class) @RequestBody Category category){
        log.info("要删除的商品信息为：{}",category);
        categoryService.save(category);
        return Result.ok();
    }

    /**
     * 修改商品信息
     * 修改商品信息的时候把缓存的数据进行删除，这是保证数据一致性的一种策略
     */
    @CacheEvict(value = {"cache:category"},key = "'Level1Categorys'")
    @PutMapping("/updateProduct")
    public Result updateProduct(@Validated(UpdateGroup.class) @RequestBody Category category){
        log.info("要修改的商品信息为：{}",category);
        categoryService.update(
                category,
                new LambdaQueryWrapper<Category>()
                        .eq(Category::getName,category.getName())
        );
        return Result.ok();
    }
}
